package com.mjk.manager.centerconf.type.impl;

import java.util.Map;
import java.util.Objects;

import com.mjk.common.util.MapUtils;
import com.mjk.manager.centerconf.type.RefreshInterface;
import com.mjk.manager.centerconf.type.RefreshType;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
 * redis刷新
 * @author jafek
 *
 */
@Component
public class RedisRefreshImpl implements RefreshInterface {

	@Override
	public void refresh(AbstractApplicationContext context,Map<String,Object> refreshData,Map<String,Object> keys) {
		Map<String, Object> redisMap = MapUtils.containsKey(refreshData, RefreshType.REDIS.getKey());
		if(!CollectionUtils.isEmpty(redisMap)){		
			RedisTemplate template = (RedisTemplate) context.getBean("redisTemplate");
			JedisConnectionFactory redisConnectionFactory = (JedisConnectionFactory) template.getConnectionFactory();
			//关闭连接池
			Objects.requireNonNull(redisConnectionFactory).destroy();
			//redisConnectionFactory.setShardInfo(null);
			String REDIS_HOST = "spring.redis.host";
			if(redisMap.containsKey(REDIS_HOST))
				redisConnectionFactory.setHostName(refreshData.get(REDIS_HOST).toString());
			String REDIS_PORT = "spring.redis.port";
			if(redisMap.containsKey(REDIS_PORT))
				redisConnectionFactory.setPort(Integer.parseInt(refreshData.get(REDIS_PORT).toString()));
			String REDIS_PWD = "spring.redis.pwd";
			if(redisMap.containsKey(REDIS_PWD))
				redisConnectionFactory.setPassword(refreshData.get(REDIS_PWD).toString());			
			//重新创建连接池
			redisConnectionFactory.afterPropertiesSet();
			template.setConnectionFactory(redisConnectionFactory);
		}
	}
	
}
